import pandas as pd
import numpy as np

#数据预处理
df1 = pd.read_csv(r'file1.csv',encoding = 'gbk')
df1 = df1.drop(70679,axis=0)#脏数据所在70679

#任务1.1
print('任务1.1:')
data_a = df1[df1['地点']=='A']
data_b = df1[df1['地点']== 'B']
data_c = df1[df1['地点'] == 'C']
data_d = df1[df1['地点'] == 'D']
data_e = df1[df1['地点'] == 'E']
#
data_a.to_csv('task1-1A.csv')
data_b.to_csv('task1-1B.csv')
data_c.to_csv('task1-1C.csv')
data_d.to_csv('task1-1D.csv')
data_e.to_csv('task1-1E.csv')
print("每台售货机销售信息保存完成")
print('\n')

#任务1.2
#计算每台售货机2017年4月份的交易额、订单量及所有售货机交易总额和订单总量
print('任务1.2：')
def timefunc(time):
    '''提取当前月份'''
    m = time.split('/')[1]
    return eval(m)

#增加新列保存月份信息
f = lambda x : timefunc(x)
df1['mounth'] = df1['支付时间'].map(f)

data_a = df1[df1['地点']=='A']#对新增的月份信息进行更新
data_b = df1[df1['地点']== 'B']
data_c = df1[df1['地点'] == 'C']
data_d = df1[df1['地点'] == 'D']
data_e = df1[df1['地点'] == 'E']

a1 = data_a.groupby('mounth')['实际金额'].sum().loc[4]
a2 = data_a.groupby('mounth')['实际金额'].count().loc[4]
print('A售货机2017年4月的交易额为' + str(a1) +' 订单量为' + str(a2))
b1 = data_b.groupby('mounth')['实际金额'].sum().loc[4]
b2 = data_b.groupby('mounth')['实际金额'].count().loc[4]
print('B售货机2017年4月的交易额为' + str(b1) +' 订单量为' + str(b2))
c1 = data_c.groupby('mounth')['实际金额'].sum().loc[4]
c2 = data_c.groupby('mounth')['实际金额'].count().loc[4]
print('C售货机2017年4月的交易额为' + str(c1) +' 订单量为' + str(c2))
d1 = data_d.groupby('mounth')['实际金额'].sum().loc[4]
d2 = data_d.groupby('mounth')['实际金额'].count().loc[4]
print('D售货机2017年4月的交易额为' + str(d1) +' 订单量为' + str(d2))
e1 = data_e.groupby('mounth')['实际金额'].sum().loc[4]
e2 = data_e.groupby('mounth')['实际金额'].count().loc[4]
print('E售货机2017年4月的交易额为' + str(e1) +' 订单量为' + str(e2))
all1 = df1.groupby('mounth')['实际金额'].sum().loc[4]
all2 = df1.groupby('mounth')['实际金额'].count().loc[4]
print('所有售货机2017年4月的交易额为' + str(all1) +' 订单量为' + str(all2))
print('\n')
#xinxi = pd.DataFrame(np.zeros((6,2)),index = ['A','B','C','D','E','ALL'],columns = ['交易额','订单数'])

#任务1.3
#根据附件 1 中的数据，提取每台售货机对应的销售数据，保存在 CSV文件中，文件名分别为“task1-1A.csv”、“task1-1B.csv”、…、task1-1E.csv”
def group1(data, key):#对给定Key进行归类并求出销售额总和
    totals = data.groupby(key)['实际金额'].sum()
    return totals

grouped = df1.groupby('地点')
m_p = grouped.apply(group1,'mounth')
print('任务1.3：')
#print('每台每月总销售额：')
#print(m_p)

def group1(data, key):
    totals = data.groupby(key)['订单号'].count()
    return totals
grouped = df1.groupby('地点')
m_d = grouped.apply(group1,'mounth')
#print('每台每月总销售量:')
#print(m_d)

print('每台每单平均交易额：')
print(m_p/m_d)

temp_day = m_p
#定义匹配天数的字典
d = {1:31, 2:28, 3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
for i in range(1, 13):
    temp_day[i] = d.get(i)
d_day = m_d / temp_day#匹配当前月份天数
print('每台日均订单量：')
print(d_day)


